<template>
  <div class="dashboard bg-gray-50 p-4">
    <el-card shadow="hover">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="130px" :inline="true">
        <el-form-item prop="followTypeId">
          <template #label>
            <div class="table-title">跟单类型:</div>
          </template>
          <el-select @change="query" v-model="form.followTypeId" clearable reserve-keyword placeholder="请选择跟单类型">
            <el-option v-for="item in followTypeList" :key="item.id" :label="item.typeName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item prop="followTypeId">
          <template #label>
            <div class="table-title">跟单人:</div>
          </template>
          <el-select @change="query" v-model="form.followUserId" clearable reserve-keyword placeholder="请选择跟单人">
            <el-option v-for="item in assistList" :key="item.userId" :label="item.realityName" :value="item.userId" />
          </el-select>
        </el-form-item>
        <el-form-item prop="followDate">
          <template #label>
            <div class="table-title">跟单时间:</div>
          </template>
          <el-date-picker
            style="width: 100%"
            v-model="dateRange"
            value-format="YYYY-MM-DD hh:mm:ss"
            type="daterange"
            @change="query"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
          ></el-date-picker>

          <el-radio-group @change="timeChange" v-model="tableFilter" style="margin-left: 10px">
            <el-radio-button value="1" label="本月">本月</el-radio-button>
            <el-radio-button value="2" label="本季">本季</el-radio-button>
            <el-radio-button value="3" label="本年">本年</el-radio-button>
          </el-radio-group>
        </el-form-item>
      </el-form>
    </el-card>
    <!-- Top Stats Cards -->
    <el-row :gutter="20" class="mb-6">
      <el-col :span="5">
        <el-card shadow="hover" class="count-card">
          <div class="flex items-center justify-between">
            <img class="gendan-img" src="@/assets/images/gendan/xiaoshou.png" alt="" />
            <div>
              <div class="text-gray-500 text-sm mb-2">跟单总数</div>
              <div class="text-2xl font-bold">{{ total }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="5">
        <el-card shadow="hover" class="count-card">
          <div class="flex items-center justify-between">
            <img class="gendan-img" src="@/assets/images/gendan/gendanzhong.png" alt="" />
            <div>
              <div class="text-gray-500 text-sm mb-2">跟单中数量</div>
              <div class="text-2xl font-bold">{{ countObj.progressCount || '-' }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="5">
        <el-card shadow="hover" class="count-card">
          <div class="flex items-center justify-between">
            <img class="gendan-img" src="@/assets/images/gendan/daishenhe.png" alt="" />
            <div>
              <div class="text-gray-500 text-sm mb-2">待审核跟单数</div>
              <div class="text-2xl font-bold">{{ countObj.waitAuditCount || '-' }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="5">
        <el-card shadow="hover" class="count-card">
          <div class="flex items-center justify-between">
            <img class="gendan-img" src="@/assets/images/gendan/success-gendan.png" alt="" />
            <div>
              <div class="text-gray-500 text-sm mb-2">成功跟单数</div>
              <div class="text-2xl font-bold">{{ countObj.completedCount || '-' }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="4">
        <el-card shadow="hover" class="count-card">
          <div class="flex items-center justify-between">
            <img class="gendan-img" src="@/assets/images/gendan/fail-gendan.png" alt="" />
            <div>
              <div class="text-gray-500 text-sm mb-2">跟单失败数</div>
              <div class="text-2xl font-bold">{{ countObj.overdueCount || '-' }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- Production Stage Cards -->
    <div class="mb-6 main">
      <template v-for="(item, index) in jzgFollowStageCountVoList" :key="index">
        <el-card @click="cardClick(item,index)" shadow="hover" class="h-full" :class="{selected:item.selected}">
          <div class="stage-label">{{ item.followStageName }}</div>
          <div class="text-center">
            <div class="flex items-center justify-between mb-4"></div>
            <div class="text-sm mb-2">
              <div>新增数: {{ item.newCount }}</div>
              <div class="text-green-500">总数: {{ item.totalCount }}</div>
              <div class="text-red-500">转化数: {{ item.convertRate }}</div>
            </div>
            <el-progress :percentage="parseInt(item.convertRate.replace('%', ''))" :color="item.color" :stroke-width="10" class="mt-2" />
          </div>
        </el-card>
      </template>
      <el-skeleton animated v-if="!jzgFollowStageCountVoList.length">
        <template #template>
          <el-skeleton-item variant="rect" v-for="i in 5" :key="i" style="width: 250px; height: 137px; margin-right: 20px" />
        </template>
      </el-skeleton>
    </div>

    <!-- Work Order Progress Table -->
    <el-card shadow="hover">
      <template #header>
        <div class="flex justify-between items-center">
          <span class="table-title">进度报表</span>
          <div>
            <el-radio-group @change="processChange" v-model="processFilter">
              <el-radio-button value="0" label="全部">全部</el-radio-button>
              <el-radio-button value="1" label="跟单中">跟单中</el-radio-button>
              <el-radio-button value="2" label="已超期">已超期</el-radio-button>
              <el-radio-button value="3" label="本月新增">本月新增</el-radio-button>
              <el-radio-button value="4" label="本月完成">本月完成</el-radio-button>
              <el-radio-button value="5" label="今日新增">今日新增</el-radio-button>
              <el-radio-button value="6" label="今日完成">今日完成</el-radio-button>
            </el-radio-group>
          </div>
        </div>
      </template>

      <el-table v-loading="loading" class="custom-table" :scrollbar-always-on="true" :data="dataSource" style="width: 100%">
        <el-table-column type="index" label="序号" width="80" />
        <el-table-column prop="clueNumber" label="跟单号" width="180">
          <template #default="scope">
            <div style="color: #409eff; cursor: pointer" @click="handleView(scope.row, scope.$index)">{{ scope.row.clueNumber }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="followDate" label="跟单日期" width="120">
          <template #default="scope">
            {{ moment(scope.row.followDate).format('YYYY-MM-DD') }}
          </template>
        </el-table-column>
        <el-table-column prop="clueName" label="项目名称" width="180" />
        <el-table-column prop="stageCycle" label="周期" width="80" >
          <template #default="{row}">
            {{ calcCycle(row) }}
          </template>
        </el-table-column>
        <el-table-column prop="estimatedTransactionAmount" label="预计成交金额" width="120" />
        <el-table-column prop="estimatedBuyDate" label="预计成交时间" width="180" />
        <el-table-column prop="supplierName" label="客户名称" width="300" />
        <el-table-column prop="sourceName" label="跟单来源" width="100" />
        <el-table-column prop="country" label="所属区域" width="100" />
        <el-table-column prop="followUserName" label="跟单人" width="80" />
        <el-table-column prop="createByName" label="报备人" width="80" />

        <!-- <el-table-column label="跟单状态" align="left" prop="clueStatus" width="110">
          <template #default="scope">
            <el-tag :type="scope.row.clueStatus == 1? 'success' : 'danger'">
              {{ scope.row.clueStatus == 1? '已分配' : '未分配' }}
            </el-tag>
          </template>
        </el-table-column> -->
        <el-table-column label="跟单进度" prop="followStageName" fixed="right" width="120">
          <template #default="{ row }">
            <el-tag type="success" @click="handleDetail(row)">
              {{ row.followStageName}}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="left" width="160" fixed="right">
          <template #default="scope">
            <div style="display: flex;align-items: baseline ;">
              <a style="color: #409eff" @click="handleRenew(scope.row)">进展</a>
              <el-divider direction="vertical"></el-divider>
              <a style="color: #409eff" @click="handleTranser(scope.row.id)">移交</a>
              <el-dropdown>
                <span class="el-dropdown-link">
                  更多
                  <el-icon class="el-icon--right">
                    <arrow-down />
                  </el-icon>
                </span>
                <template #dropdown>
                  <el-dropdown-menu>
                    <!-- <el-dropdown-item  @click="handleReceive(scope.row)">分配</el-dropdown-item> -->
                    <!-- <el-dropdown-item  @click="handleTranser(scope.row)">移交</el-dropdown-item> -->
                    <el-dropdown-item  @click="handleViewHistory(scope.row)">历史</el-dropdown-item>
                    <el-dropdown-item  @click="handleEdit(scope.row)">编辑</el-dropdown-item>
                    <el-dropdown-item v-if="scope.row.clueStatus == 0"  @click="handleDelete(scope.row.id)">删除</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <pagination
          v-show="total > 0"
          :total="total"
          v-model:page.sync="form.pageNum"
          v-model:limit.sync="form.pageSize"
          @pagination="getList"
        />
    </el-card>
    <receiveForm ref="receiveForm" @ok="getList"></receiveForm>
    <historyForm ref="historyForm"></historyForm>
    <transer ref="transer" @ok="getList"></transer>
    <historyForm ref="historyForm"></historyForm>
    <addForm ref="modelForm" @ok="addOk"></addForm>
    <progressForm ref="progressForm" @ok="getList"></progressForm>
    <trackingDetail ref="trackingDetail"></trackingDetail>
    <addContractForm ref="addContractForm"></addContractForm>
  </div>
</template>

<script>
import { listFollowType } from '@/api/goods/followType';
import { listByTypeId } from '@/api/goods/followStage';
import { listClue, listcount } from '@/api/goods/clue';
import { getUserNotPermission } from '@/api/system/user';
import request from '@/utils/request';
import moment from'moment';

import addForm from '@/views/goods/clue/modules/addForm.vue';
import transer from '@/views/goods/clue/modules/transer.vue';
import historyForm from '@/views/goods/clue/modules/historyForm.vue';
import receiveForm from '@/views/goods/clue/modules/receiveForm.vue';
import progressForm from './components/progressForm.vue';
import trackingDetail from '@/views/goods/clue/modules/trackingDetail.vue';
import addContractForm from '@/views/goods/crmContract/modules/addForm.vue';

export default {
  name: 'User',
  components: {
    addForm,
    transer,
    historyForm,
    receiveForm,
    progressForm,
    trackingDetail,
    addContractForm
  },
  data() {
    return {
      tableFilter: '1',
      processFilter: '0',
      followStatus: [],
      followTypeList: [],
      assistList: [],
      dataSource: [],
      loading: false,
      total: 0,
      countObj: {},
      jzgFollowStageCountVoList: [],
      dateRange: [moment().startOf('month').format('YYYY-MM-DD hh:mm:ss'), moment().endOf('month').format('YYYY-MM-DD hh:mm:ss')],
      form: {
        followTypeId: '',
        followType: '',
        followUserId: '',
        pageNum: 1,
        pageSize: 10
      },
      rules: {}
    };
  },
  created() {
    this.getFollowType().then(() => {
      this.getList();
      this.getListcount();
      this.getUserPermission();
    });
  },
  methods: {
    moment,
    
    handleDetail(row) {
      this.$refs.trackingDetail.detail(row);
    },
    timeChange(val) {
      console.log(typeof(val));
      switch (val) {
        // 本月
        case '1':
          this.dateRange = [moment().startOf('month').format('YYYY-MM-DD hh:mm:ss'), moment().endOf('month').format('YYYY-MM-DD hh:mm:ss')];
          break;
        case '2':
          // 本季
          this.dateRange = [moment().startOf('quarter').format('YYYY-MM-DD hh:mm:ss'), moment().endOf('quarter').format('YYYY-MM-DD hh:mm:ss')];
          break;
        case '3':
          // 本年
          this.dateRange = [moment().startOf('year').format('YYYY-MM-DD hh:mm:ss'), moment().endOf('year').format('YYYY-MM-DD hh:mm:ss')];
          break;
        default:
          break;
      }
      this.$forceUpdate();

      this.getList();
      this.getListcount();

    },
    processChange(val) {
      switch (val) {
        // 全部
        case '0':
          // this.dateRange = [];
          this.form.followStatus = '';
          break;
        // 跟单中
        case '1':
          // this.dateRange = [];
          this.form.followStatus = 1;
          break;
        // 已超期
        case '2':
          this.form.followStatus = 4;
          // this.dateRange = [];
          break;
        // 本月新增
        case '3':
          this.form.followStatus = '';
          this.dateRange = [moment().startOf('month').format('YYYY-MM-DD hh:mm:ss'), moment().endOf('month').format('YYYY-MM-DD hh:mm:ss')];
          break;
        // 本月完成
        case '4':
          this.form.followStatus = 3;
          this.dateRange = [moment().startOf('month').format('YYYY-MM-DD hh:mm:ss'), moment().endOf('month').format('YYYY-MM-DD hh:mm:ss')];
          break;
        // 今日新增
        case '5':
          this.form.followStatus = '';
          this.dateRange = [moment().format('YYYY-MM-DD') + '00:00:00', moment().format('YYYY-MM-DD') + '23:59:59'];
          break;
        // 今日完成
        case '6':
          this.form.followStatus = 3;
          this.dateRange = [moment().format('YYYY-MM-DD') + '00:00:00', moment().format('YYYY-MM-DD') + '23:59:59'];
          break;

        default:
          break;
      }
      this.getList();
      this.getListcount();
    },
    cardClick(item,index) {
      this.form.followStageId = item.followStageId;
      this.jzgFollowStageCountVoList.forEach((val,idx) => {
        if (index == idx) {
          item.selected = !item.selected;
        } else {
          val.selected = false;
        }
      })
      this.getList();
    },
    query() {
      this.jzgFollowStageCountVoList = []
      this.getList();
      this.getListcount();
    },
    getFollowType() {
      return new Promise((resolve, reject) => {
        listFollowType({
          pageSize: 9999,
          pageNum: 1,
          typeCategory:1
        })
       .then((res) => {
            this.followTypeList = res.rows || [];
            if (this.followTypeList.length > 0) {
              this.form.followTypeId = this.followTypeList[0].id;
            }
            resolve();
          })
       .catch((error) => {
            reject(error);
          });
      });
    },
    currentStep(row) {
      let index = row.jzgFollowStageVoList.findIndex((item) => item.id == row.followStageId);
      return index;
    },
    getQueryParams() {
      let params = Object.assign({ params: {} }, this.form);
      if (this.dateRange && this.dateRange.length) {
        params.params['createBeginTime'] = this.dateRange[0] + ' 00:00:00';
        params.params['createEndTime'] = this.dateRange[1] + ' 23:59:59';
      }
      return params;
    },
    getUserPermission() {
      getUserNotPermission()
       .then((res) => {
          this.assistList = res;
        })
       .catch((err) => {
          console.log(err);
        });
    },
    getFollowStatus(id) {
      listByTypeId(id)
       .then((res) => {
          this.followStatus = res || [];
        })
       .catch((error) => {
          console.error(error);
        });
    },
    
    listByTypeId(id) {
      return new Promise((resolve, reject) => {
        listByTypeId(id).then(res => {
          resolve(res)
        })
      })
    },
    getList() {
      this.loading = true;
      let params = this.getQueryParams();
      listClue(params)
       .then((res) => {
          this.loading = false;
         this.dataSource = res.rows || [];
          this.total = res.total || 0;
        })
       .catch((error) => {
          console.error(error);
        });
    },
    getListcount() {
      let params = this.getQueryParams();
      listcount(params)
       .then((res) => {
          this.countObj = res.data || {};
          this.jzgFollowStageCountVoList = res.data.jzgFollowStageCountVoList || [];
        })
       .catch((error) => {
          console.error(error);
        });
    },
    handleReceive(row) {
      this.$refs.receiveForm.edit(row);
    },
    handleTranser(row) {
      this.$refs.transer.edit(row);
    },
    handleViewHistory(row, index) {
      this.$refs.historyForm.view(row);
    },
    handleView(row, index) {
      this.$refs.modelForm.view(row, index, this.dataSource);
    },
    handleEdit(row) {
      this.$refs.modelForm.edit(row);
    },
    // 续费
    handleRenew(row) {
      this.$refs.progressForm.edit(row);
    },
    handleDelete(ids) {
      this.$modal
       .confirm('确定删除？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
       .then(() => {
          request({
            url: '/clue/deleteClues',
            method: 'delete'
          })
         .then((res) => {
            if (res.code == 200) {
              this.$modal.msgSuccess('删除成功');
              this.getList();
            } else {
              this.$modal.msgError(res.msg);
            }
          });
        })
       .catch(() => {});
    },
    /**
     * 计算周期
     */
    calcCycle(info) {
      console.log(info, 'form');
      if(info.jzgFollowStageVoList && info.jzgFollowStageVoList.length > 0){
        let item = info.jzgFollowStageVoList.find((v) => v.id == info.followStageId);
        if (item) {
          let endDate = item.progressCoefficient == '100%' ? moment(info.orderFollowDate).format('YYYY-MM-DD') : moment().format('YYYY-MM-DD');
          let starDate = moment(info.followDate).format('YYYY-MM-DD');
          console.log('777',777);
          return moment(endDate).diff(starDate, 'days') + 1;
        }
      }

      return '';
    },
    
    // 新增成功回调
    async addOk(form) {
      this.getList();
      // 判断跟单阶段是否到合同，如果是则继续创建合同
      const stage = await this.listByTypeId(form.followTypeId);
      const item = stage.find(v => v.id === form.followStageId);
      if (item && item.stageProcess == '1') {
        
      this.$modal
        .confirm('是否继续创建合同？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .then(() => {
          this.$refs.addContractForm.link(form);
        })
        .catch(() => {});
      }

    }
  }
};
</script>

<style scoped>
.dashboard {
  min-height: 100vh;
}

.el-card {
  margin-bottom: 1rem;
}

.stage-label {
  font-size: 0.875rem;
  color: #606266;
  position: absolute;
  left: 0;
  top: 0;
  background-color: #0c7fc2;
  padding: 4px 16px;
  color: #fff;
  border-bottom-right-radius: 27px;
  min-width: 60px;
  text-align: center;
}
.h-full {
  position: relative;
  width: 250px;
  margin-right: 20px;
  display: inline-block;
  cursor: pointer;
}
.line {
  width: 48px;
  height: 2px;
  background-color: red;
  margin-top: 28px;
  align-self: baseline;
}
.gendan-img {
  width: 60px;
}
.table-title {
  color: #409eff;
  font-size: 16px;
  font-weight: bold;
}
.main {
  white-space: nowrap;
  width: 100%;
  overflow-x: auto;
  overflow-y: hidden;
  overflow-x: auto;
  scroll-behavior: smooth;
  -webkit-overflow-scrolling: touch;
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none; /* Internet Explorer 10+ */
}
/* 为div添加滚动条样式 */
.main:hover::-webkit-scrollbar{
    height: 14px; /* 滚动条宽度 */
}
 
.main::-webkit-scrollbar-thumb {
    background-color: #409eff!important;
    border-radius: 6px; /* 滚动条圆角 */
}
.count-card{
  height: 100px;
}
</style>
<style>
.custom-table .el-table__header-wrapper .cell {
  font-size: 15px;
}

.custom-table .el-table__header {
  color: red; /* 修改表头字体颜色 */
}
.selected{
  background-color: #409;
  color:#fff;
}
</style>